package com.mlethe.android.demo.seattable.presenter;

import androidx.fragment.app.FragmentActivity;

import com.mlethe.android.demo.R;
import com.mlethe.android.demo.seattable.base.BasePresenter;
import com.mlethe.android.demo.seattable.entity.Hall;
import com.mlethe.android.demo.seattable.entity.Obj;
import com.mlethe.android.demo.seattable.entity.Result;
import com.mlethe.android.demo.seattable.model.MovieModel;
import com.mlethe.android.demo.seattable.view.MovieSessionView;
import com.mlethe.library.net.callback.Consumer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class MovieSessionPresenter extends BasePresenter<MovieSessionView> {

    private MovieModel movieModel;

    public MovieSessionPresenter(FragmentActivity activity) {
        super(activity);
        movieModel = new MovieModel();
    }

    public void cinemaPlayInfo(String playIds) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("play_id", playIds);
        movieModel.cinemaPlayInfo(map)
                .subscribe(new Consumer<Result<Obj<List<Hall>>>>() {
                    @Override
                    public void onSuccess(Result<Obj<List<Hall>>> objResult) {
                        if (!objResult.isOk()) {
                            getView().fail(objResult.getContent());
                        } else if (!objResult.getObject().getRes().isOk()) {
                            getView().fail(objResult.getObject().getRes().getErrorMessage());
                        } else {
                            getView().success(handleData(objResult.getObject().getRes().getData()));
                        }
                    }

                    @Override
                    public void onFailure(Throwable throwable) {
                        throwable.printStackTrace();
                        getView().fail(mFragmentActivity.getString(R.string.empty_network_error));
                    }
                });
    }

    private SortedMap<String, ArrayList<Hall>> handleData(List<Hall> result) {
        SortedMap<String, ArrayList<Hall>> map = new TreeMap<>();
        for (Hall hall: result) {
            boolean flag = false;
            for (Map.Entry<String, ArrayList<Hall>> entry: map.entrySet()) {
                if (hall.getBusinessDate().equals(entry.getKey())) {
                    flag = true;
                    entry.getValue().add(hall);
                    break;
                }
            }
            if (!flag) {
                ArrayList<Hall> list = new ArrayList<>();
                list.add(hall);
                map.put(hall.getBusinessDate(), list);
            }
        }
        return map;
    }

}
